package com.mxdx.edu.common;

import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletInputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Map;

/**
 * @author: liujianlu
 * @Description:
 * @Date: Created in 20:16 2018/7/30
 */
public class VnHttpForwardHanlder {

    private HttpServletRequest request;
    private HttpServletResponse response;
    private String targetAddr;
    private Map<String, Object> returnData;
    private int timelimit = 60;

    public HttpServletRequest getRequest() {
        return this.request;
    }

    public void setRequest(HttpServletRequest request) {
        this.request = request;
    }

    public HttpServletResponse getResponse() {
        return this.response;
    }

    public void setResponse(HttpServletResponse response) {
        this.response = response;
    }

    public String getTargetAddr() {
        return this.targetAddr;
    }

    public void setTargetAddr(String targetAddr) {
        this.targetAddr = targetAddr;
    }

    public Map<?, ?> getReturnData() {
        return this.returnData;
    }

    public void setReturnData(Map<String, Object> returnData) {
        this.returnData = returnData;
    }

    public int getTimelimit() {
        return this.timelimit;
    }

    public void setTimelimit(int timelimit) {
        this.timelimit = timelimit;
    }

    public VnHttpForwardHanlder(HttpServletResponse rsp, HttpServletRequest req, String addr) {
        this.request = req;
        this.targetAddr = addr;
        this.response = rsp;
    }

    public VnHttpForwardHanlder() {
    }

    protected boolean preCheck() {
        if(this.targetAddr != null && !this.targetAddr.equals("")) {
            if(this.request != null && !this.request.equals("")) {
                return true;
            } else {
                this.returnData.put("ERR_CD", "0002");
                return false;
            }
        } else {
            this.returnData.put("ERR_CD", "0001");
            return false;
        }
    }

    protected byte[] receiveData() throws Exception {
        byte[] data = new byte[0];
        if(this.request.getMethod() == "GET") {
            String msgLen = this.request.getQueryString();
            if(msgLen != null) {
                data = msgLen.getBytes();
            }
        } else {
            int msgLen1 = this.request.getContentLength();
            if(msgLen1 <= 0) {
                msgLen1 = this.request.getInputStream().available();
            }

            data = new byte[msgLen1];
            data = InputStreamToByte(this.request.getInputStream());
        }

        return data;
    }

    public static byte[] InputStreamToByte(InputStream iStrm) throws IOException {
        ByteArrayOutputStream bytestream = new ByteArrayOutputStream();

        int ch;
        while((ch = iStrm.read()) != -1) {
            bytestream.write(ch);
        }

        byte[] imgdata = bytestream.toByteArray();
        bytestream.close();
        return imgdata;
    }

    public void request() throws Exception {
        if(this.preCheck()) {
            ServletInputStream in = null;
            ServletOutputStream out = null;

            try {
                in = this.request.getInputStream();
                out = this.response.getOutputStream();
                byte[] e = this.receiveData();
                JSONObject haderMap = new JSONObject();
                Enumeration headerNames = this.request.getHeaderNames();

                String err;
                while(headerNames.hasMoreElements()) {
                    err = (String)headerNames.nextElement();
                    String value = this.request.getHeader(err);
                    haderMap.put(err, value);
                }

                this.returnData = VnHttpConnector.request(this.targetAddr, e, this.request.getMethod(), this.timelimit, haderMap);
                this.setResponseHeader();
                if(this.returnData.get("ERR_CD") != null){
                    err = (String)this.returnData.get("ERR_CD");
                    if(!"0000".equalsIgnoreCase(err) && StringUtils.isNotBlank(err)) {
                        this.response.sendError(500);
                        return;
                    }
                }
                out.write((byte[])this.returnData.get("MESSAGE"));
                out.flush();
            } catch (Exception var20) {
                throw new Exception("route exception" + var20.getMessage());
            } finally {
                if(in != null) {
                    try {
                        in.close();
                    } catch (Exception var19) {
                        throw new Exception("route exception in.close()" + var19.getMessage());
                    }
                }

                if(out != null) {
                    try {
                        out.close();
                    } catch (Exception var18) {
                        throw new Exception("route exception out.close()" + var18.getMessage());
                    }
                }

            }

        }
    }

    private void setResponseHeader() {
        if(this.returnData == null) {
            this.returnData.put("ERR_CD", "0004");
        } else {
            Map resHeaders = (Map)this.returnData.get("HEAD");
            if(resHeaders != null) {
                Iterator i = resHeaders.keySet().iterator();
                String key = null;
                String value = null;

                while(i.hasNext()) {
                    key = (String)i.next();
                    value = (String)resHeaders.get(key);
                    this.response.setHeader(key, value);
                }
            }

            this.response.setStatus(((Integer)this.returnData.get("STATUS")).intValue());
        }
    }
}
